'use strict';

const Service = require('egg').Service;
const { ObjectId } = require("mongodb");

class MovieService extends Service {
    async find(m) {
        const db = this.app.mongodb;
        const res = await db.collection(m).find().toArray();
        return res;
    }
    async getMovieDetail(obj) {
        const db = this.app.mongodb;
        const tables = ["top250", "inTheaters", "comingSoon"];
        var sum = [];
        // await Promise.all(tables.map(async item => {
        //     if (obj.id) {
        //         var res = await db.collection(item).find({ _id: obj.id }).toArray();
        //         sum.push(...res)
        //     } else if (obj.keyword) {
        //         var keyword = new RegExp(obj.keyword);
        /**
         * 只能以正则的形式去查
         * find({ title: "你" }) error
         * find({ title: /你/ }) success
         */
        //         var res = await db.collection(item).find({ title: keyword }).toArray();
        //         sum.push(...res)
        //     }

        // }))
        for (var i = 0; i < tables.length; i++) {
            if (obj.id) {
                var res = await db.collection(tables[i]).find({ _id: obj.id }).toArray();
                sum.push(...res)
            } else if (obj.keyword) {
                var keyword = new RegExp(obj.keyword);
                /**
                 * 只能以正则的形式去查
                 * find({ title: "你" }) error
                 * find({ title: /你/ }) success
                 */
                var res = await db.collection(tables[i]).find({ title: keyword }).toArray();
                sum.push(...res)
            }
        }
        return sum;
    }
    // async getMovieSearch(keyword) {
    //     const db = this.app.mongodb;
    //     const tables = ["top250", "inTheaters", "comingSoon"];

    //     keyword = new RegExp(keyword);
    //     var sum = [];
    //     await Promise.all(tables.map(async item => {
    //         var res = await db.collection(item).find({ title: keyword }).toArray();
    //         sum.push(...res)
    //     }))
    //     return sum;
    // }
}

module.exports = MovieService;
